import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpSever {
    private ServerSocket serverSocket = null;
    public TcpSever(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("TCPserver 开始！");
        while(true){
            Socket socket = serverSocket.accept();
            processConnection(socket);
        }
    }

    private void processConnection(Socket socket) {
        System.out.printf("[%s %d] 客户端上线\n",socket.getInetAddress(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s %d] 客户端下线\n",socket.getInetAddress(),socket.getPort());
                    break;
                }
                String request = scanner.next();
                String response = process(request);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s %d] req: %s res: %s\n",socket.getInetAddress(),socket.getPort(),
                        request,response);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpSever tcpSever = new TcpSever(9091);
        tcpSever.start();
    }
}
